import { useState, useEffect, useRef } from 'react';
import { Layout, Table, Spin, message, Button, Input } from 'antd';
import axios from 'axios';
import { API_BASE_URL } from '../config';
import { ReloadOutlined, LeftOutlined, RightOutlined } from '@ant-design/icons';
import { MdOutlineFactory } from 'react-icons/md';
import { FullscreenOutlined, EditOutlined } from '@ant-design/icons';
import { useContext } from 'react';
import { TabsContext } from '../contexts/TabsContext';

// 添加自定义CSS样式
const customStyles = `
  .product-process-container {
    height: 100%;
    background-color: #fff;
    border-radius: 4px;
    overflow: hidden;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  }
  
  .data-table {
    width: 100%;
  }
  
  .table-row-normal-height td {
    padding: 16px 8px;
  }
  
  .table-row-compact-height td {
    padding: 8px;
  }
  
  .compact-table .ant-table-thead > tr > th {
    padding: 8px;
  }
  
  .pagination-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px;
    border-top: 1px solid #e8e8e8;
    background: #fff;
  }
  
  .table-header-actions {
    padding: 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .action-buttons {
    display: flex;
    gap: 8px;
  }

  .horizontal-scroll-container {
    overflow-x: auto !important;
    overflow-y: hidden !important;
    display: block !important;
  }
  
  .horizontal-scroll-container::-webkit-scrollbar {
    height: 8px !important;
    background-color: #f1f1f1 !important;
    display: block !important;
  }
  
  .horizontal-scroll-container::-webkit-scrollbar-thumb {
    background-color: #c1c1c1 !important;
    border-radius: 4px !important;
  }
  
  .horizontal-scroll-container::-webkit-scrollbar-thumb:hover {
    background-color: #a8a8a8 !important;
  }
  
  .ant-table-wrapper, .ant-table, .ant-table-container {
    min-width: 1200px !important;
  }
  
  /* 美化表格边框和表头 */
  .ant-table {
    border: 1px solid #e8e8e8 !important;
  }
  
  .ant-table-thead > tr > th {
    background-color: #f7f7f7 !important;
    font-weight: bold !important;
    border-bottom: 1px solid #e8e8e8 !important;
  }
  
  @media screen and (max-width: 576px) {
    .product-process-container {
      margin: 0;
      border-radius: 0;
    }
    
    .horizontal-scroll-container .ant-table-wrapper, 
    .horizontal-scroll-container .ant-table, 
    .horizontal-scroll-container .ant-table-container {
      min-width: 800px !important;
    }
    
    .ant-table-cell {
      padding: 4px !important;
      font-size: 12px !important;
    }
  }
`;

const { Content } = Layout;

const ProductProcess = () => {
  // 使用TabsContext上下文
  const { addTab } = useContext(TabsContext);
  
  // 表格容器引用，用于横向滚动
  const tableContainerRef = useRef(null);
  
  // 状态管理
  const [loading, setLoading] = useState(false);
  const [processList, setProcessList] = useState([]);
  const [productInfoMap, setProductInfoMap] = useState({});
  const [isMobile, setIsMobile] = useState(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });
  
  // 新增状态 - 模板信息映射
  const [templateInfoMap, setTemplateInfoMap] = useState({});
  
  // 分页相关状态
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const inputRef = useRef(null);

  // 检测是否为移动设备
  useEffect(() => {
    const checkIsMobile = () => {
      setIsMobile(window.innerWidth <= 576);
    };
    
    checkIsMobile();
    window.addEventListener('resize', checkIsMobile);
    
    return () => {
      window.removeEventListener('resize', checkIsMobile);
    };
  }, []);

  // 获取产品工艺列表
  const fetchProductProcessList = async (page = 1, pageSize = 10) => {
    setLoading(true);
    try {
      const response = await axios.get(`${API_BASE_URL}/api/product_process_route`, {
        params: {
          page,
          size: pageSize
        }
      });
      
      if (response.data && response.data.code === 200) {
        const items = response.data.data.items || [];
        
        // 处理返回的数据，确保所有必要字段都存在
        const processedItems = items.map(item => ({
          ...item,
          key: item.id,
          name: item.name || '未命名',
          code: item.code || '-',
          total_work_hour: item.total_work_hour || 0,
          create_time: item.create_time || null
        }));
        
        console.log('产品工艺列表数据:', processedItems);
        setProcessList(processedItems);
        
        // 更新分页状态
        setPagination({
          ...pagination,
          current: page,
          pageSize: pageSize,
          total: response.data.data.total || 0
        });
        setCurrentPage(page);
        
        // 收集所有的product_id，后续获取产品详情
        const productIds = processedItems.map(item => item.product_id).filter(id => id);
        if (productIds.length > 0) {
          fetchProductInfos(productIds);
        }

        // 获取模板信息
        processedItems.forEach(item => {
          fetchProcessDetail(item.id);
        });
      } else {
        message.error('获取产品工艺列表失败: ' + (response.data.message || '未知错误'));
      }
    } catch (error) {
      console.error('获取产品工艺列表错误:', error);
      message.error('获取产品工艺列表失败: ' + (error.message || '网络错误'));
    } finally {
      setLoading(false);
    }
  };

  // 获取产品详细信息
  const fetchProductInfos = async (productIds) => {
    try {
      // 创建一个临时的产品信息映射
      const tempProductInfoMap = { ...productInfoMap };
      
      // 并行获取每个产品的详细信息
      const promises = productIds.map(async (id) => {
        if (tempProductInfoMap[id]) return; // 如果已经有了，就不再获取
        
        try {
          const response = await axios.get(`${API_BASE_URL}/api/product_info/${id}`);
          if (response.data && response.data.code === 200) {
            tempProductInfoMap[id] = response.data.data;
          }
        } catch (error) {
          console.error(`获取产品 ${id} 详情失败:`, error);
        }
      });
      
      // 等待所有请求完成
      await Promise.all(promises);
      
      // 更新产品信息映射
      setProductInfoMap(tempProductInfoMap);
    } catch (error) {
      console.error('获取产品信息错误:', error);
    }
  };

  // 获取工艺详情以及模板信息
  const fetchProcessDetail = async (routeId) => {
    try {
      // 先获取工艺路线详情
      const routeResponse = await axios.get(`${API_BASE_URL}/api/product_process_route/${routeId}/detail`);
      
      if (routeResponse.data && routeResponse.data.code === 200) {
        const routeDetail = routeResponse.data.data;
        const templateId = routeDetail.template_id;
        
        // 如果有模板ID，则获取模板详情
        if (templateId) {
          fetchTemplateInfo(templateId, routeId);
        }
      }
    } catch (error) {
      console.error(`获取工艺详情错误 (ID: ${routeId}):`, error);
    }
  };

  // 获取模板详情
  const fetchTemplateInfo = async (templateId, routeId) => {
    try {
      const templateResponse = await axios.get(`${API_BASE_URL}/api/process_template_info/${templateId}`);
      
      if (templateResponse.data && templateResponse.data.code === 200) {
        const templateDetail = templateResponse.data.data;
        
        // 更新模板信息映射
        setTemplateInfoMap(prev => ({
          ...prev,
          [routeId]: templateDetail
        }));
      }
    } catch (error) {
      console.error(`获取模板详情错误 (ID: ${templateId}):`, error);
    }
  };

  // 处理页码变化
  const handlePageChange = (page) => {
    setCurrentPage(page);
    fetchProductProcessList(page, pageSize);
  };

  // 处理页码输入
  const handlePageInputChange = (e) => {
    const value = parseInt(e.target.value, 10);
    if (!isNaN(value)) {
      setCurrentPage(value);
    }
  };

  // 处理页码输入框按键事件
  const handlePageInputKeyPress = (e) => {
    if (e.key === 'Enter') {
      const value = parseInt(e.target.value, 10);
      if (!isNaN(value) && value > 0 && value <= Math.ceil(pagination.total / pageSize)) {
        fetchProductProcessList(value, pageSize);
      }
    }
  };

  // 前一页
  const goPrevPage = () => {
    if (currentPage > 1) {
      const prevPage = currentPage - 1;
      setCurrentPage(prevPage);
      fetchProductProcessList(prevPage, pageSize);
    }
  };

  // 后一页
  const goNextPage = () => {
    if (currentPage < Math.ceil(pagination.total / pageSize)) {
      const nextPage = currentPage + 1;
      setCurrentPage(nextPage);
      fetchProductProcessList(nextPage, pageSize);
    }
  };

  // 打开工艺详情页签
  const openProcessDetail = (record) => {
    // 打开一个新的页签，用于展示工艺详情
    const tabKey = `processDetail-${record.id}`;
    const tabTitle = `${record.code}工艺`;
    addTab(tabKey, tabTitle, 'ProcessDetail', { routeId: record.id, code: record.code });
  };

  // 打开模板详情页签
  const openTemplateDetail = (templateInfo, routeId) => {
    if (!templateInfo || !templateInfo.id) return;
    
    // 打开一个新的页签，用于展示模板详情
    const tabKey = `templateDetail-${templateInfo.id}`;
    const tabTitle = `${templateInfo.code}`;
    addTab(tabKey, tabTitle, 'ProcessTemplateDetail', { templateId: templateInfo.id });
  };

  // 打开产品详情
  const openProductDetail = (productId) => {
    if (!productId) return;
    
    // 获取产品信息
    const productInfo = productInfoMap[productId] || {};
    
    // 打开一个新的页签，用于展示产品详情
    const tabKey = `productDetail-${productId}`;
    const tabTitle = `${productInfo.code || '产品'}`;
    addTab(tabKey, tabTitle, 'ProductDetail', { productId });
  };

  // 列定义
  const getTableColumns = () => {
    const baseColumns = [
      {
        title: '编码',
        dataIndex: 'code',
        key: 'code',
        align: 'center',
        ellipsis: true,
        render: (text, record) => (
          <span 
            style={{ 
              display: 'block', 
              width: '100%', 
              textAlign: 'center', 
              cursor: 'pointer',
              color: '#1766a3'
            }}
            onClick={() => openProcessDetail(record)}
          >
            {text || '-'}
          </span>
        )
      },
      {
        title: '名称',
        dataIndex: 'name',
        key: 'name',
        align: 'left',
        ellipsis: true,
        render: (text, record) => (
          <span style={{ display: 'flex', alignItems: 'center' }}>
            <MdOutlineFactory 
              style={{ 
                fontSize: isMobile ? '12px' : '16px', 
                marginRight: isMobile ? '4px' : '8px',
                color: '#1766a3'
              }} 
            />
            <span>{text}</span>
          </span>
        )
      },
      {
        title: '总工时',
        dataIndex: 'total_work_hour',
        key: 'total_work_hour',
        align: 'center',
        ellipsis: true,
        render: (text) => <span style={{ display: 'block', width: '100%', textAlign: 'center' }}>{text || 0} h</span>
      }
    ];
    
    // 移动端显示核心列
    if (isMobile) {
      return baseColumns;
    }
    
    // 桌面端显示完整列
    return [
      ...baseColumns,
      {
        title: '关联产品',
        dataIndex: 'product_id',
        key: 'product_id',
        align: 'center',
        ellipsis: true,
        render: (productId) => {
          const productInfo = productInfoMap[productId] || {};
          return (
            <span 
              style={{ 
                cursor: 'pointer', 
                color: productInfo.code ? '#1766a3' : 'inherit',
                display: 'block', 
                width: '100%', 
                textAlign: 'center'
              }}
              onClick={productInfo.code ? () => openProductDetail(productId) : null}
            >
              {productInfo.code || '无'}
            </span>
          );
        }
      },
      {
        title: '产品名称',
        dataIndex: 'product_id',
        key: 'product_name',
        align: 'left',
        ellipsis: true,
        render: (productId) => {
          const productInfo = productInfoMap[productId] || {};
          return <span>{productInfo.name || '-'}</span>;
        }
      },
      {
        title: '工艺模板编码',
        dataIndex: 'id',
        key: 'template_id',
        align: 'center',
        ellipsis: true,
        render: (routeId) => {
          const templateInfo = templateInfoMap[routeId] || {};
          return (
            <span 
              style={{ 
                cursor: templateInfo.code ? 'pointer' : 'default', 
                color: templateInfo.code ? '#1766a3' : 'inherit',
                display: 'block',
                width: '100%',
                textAlign: 'center'
              }}
              onClick={templateInfo.code ? () => openTemplateDetail(templateInfo, routeId) : null}
            >
              {templateInfo.code || '无'}
            </span>
          );
        }
      },
      {
        title: '模板名称',
        dataIndex: 'id',
        key: 'template_name',
        align: 'left',
        ellipsis: true,
        render: (routeId) => {
          const templateInfo = templateInfoMap[routeId] || {};
          return <span>{templateInfo.name || '-'}</span>;
        }
      },
      {
        title: '创建时间',
        dataIndex: 'create_time',
        key: 'create_time',
        align: 'center',
        ellipsis: true,
        render: (text) => {
          if (!text) return <span style={{ display: 'block', width: '100%', textAlign: 'center' }}>-</span>;
          try {
            const date = new Date(text);
            if (!isNaN(date.getTime())) {
              return <span style={{ display: 'block', width: '100%', textAlign: 'center' }}>
                {date.toLocaleString('zh-CN', {
                  year: 'numeric',
                  month: '2-digit',
                  day: '2-digit',
                  hour: '2-digit',
                  minute: '2-digit',
                  second: '2-digit',
                  hour12: false
                }).replace(/\//g, '-')}
              </span>;
            }
            return <span style={{ display: 'block', width: '100%', textAlign: 'center' }}>{text}</span>;
          } catch (error) {
            console.error('日期格式化错误:', error);
            return <span style={{ display: 'block', width: '100%', textAlign: 'center' }}>{text || '-'}</span>;
          }
        }
      }
    ];
  };

  // 根据数据行数确定行高
  const getRowClassName = () => {
    const dataLength = processList.length;
    if (dataLength >= 10 || isMobile) {
      return "table-row-compact-height";
    }
    return "table-row-normal-height";
  };

  // 组件挂载时加载数据
  useEffect(() => {
    fetchProductProcessList();
  }, []);

  // 刷新数据
  const handleRefresh = () => {
    fetchProductProcessList(pagination.current, pagination.pageSize);
  };

  return (
    <Layout className={`product-process-container ${isMobile ? 'mobile-layout' : ''}`}>
      <style dangerouslySetInnerHTML={{ __html: customStyles }} />
      <Content style={{ padding: '0', height: '100%' }}>
        <div style={{ 
          height: '100%',
          display: 'flex',
          flexDirection: 'column'
        }}>
          {/* 标题栏 */}
          <div className="table-header-actions">
            <div style={{ 
              fontWeight: 'bold', 
              fontSize: isMobile ? '14px' : '18px',
              display: 'flex',
              alignItems: 'center',
              color: '#1766a3'
            }}>
              <MdOutlineFactory style={{ marginRight: '8px' }} />
              <span>产品工艺列表</span>
            </div>
            <div className="action-buttons">
            <Button 
              icon={<ReloadOutlined />}
              onClick={handleRefresh}
              size={isMobile ? 'small' : 'middle'}
              title="刷新数据"
            >
              刷新
            </Button>
            </div>
          </div>
          
          {/* 表格容器 */}
          <div style={{ flex: 1, overflow: 'auto' }}>
            <div 
              ref={tableContainerRef}
              className="horizontal-scroll-container"
              data-rows-count={processList.length > 10 ? "many" : "few"}
            >
                <Spin spinning={loading}>
                  <Table
                    className={`data-table ${processList.length >= 10 || isMobile ? 'compact-table' : ''}`}
                    dataSource={processList}
                    columns={getTableColumns()}
                    pagination={false}
                    rowClassName={getRowClassName}
                    size={isMobile || processList.length >= 10 ? 'small' : 'middle'}
                    bordered={true}
                    scroll={{ x: processList.length > 0 ? (isMobile ? 800 : 'max-content') : undefined }}
                    tableLayout="auto"
                    locale={{ emptyText: '暂无数据' }}
                  />
                </Spin>
            </div>
          </div>
          
          {/* 自定义分页 */}
          <div className="pagination-container">
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <span>共 {pagination.total} 条，{Math.ceil(pagination.total / pageSize)} 页</span>
            </div>
            
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <Button 
                icon={<LeftOutlined />}
                onClick={goPrevPage}
                disabled={currentPage === 1}
                style={{ marginRight: '8px' }}
              />
              
              <Input
                ref={inputRef}
                style={{ width: '50px', textAlign: 'center', margin: '0 8px' }}
                value={currentPage}
                onChange={handlePageInputChange}
                onKeyPress={handlePageInputKeyPress}
              />
              
              <span style={{ margin: '0 8px' }}>/ {Math.ceil(pagination.total / pageSize)}</span>
              
              <Button 
                icon={<RightOutlined />}
                onClick={goNextPage}
                disabled={currentPage >= Math.ceil(pagination.total / pageSize)}
                style={{ marginLeft: '8px', marginRight: '8px' }}
              />
              
              <span style={{ marginLeft: '8px' }}>
                {pageSize} / 页
                  </span>
            </div>
          </div>
        </div>
      </Content>
    </Layout>
  );
};

export default ProductProcess; 